package neo.core.common;

import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletRequest;

import neo.core.Constants;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.webwork.config.Configuration;
import com.opensymphony.webwork.dispatcher.multipart.MultiPartRequestWrapper;
import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.ActionInvocation;
import com.opensymphony.xwork.interceptor.Interceptor;

public class ExceptionInterceptor implements Interceptor {

	protected final Log log = LogFactory.getLog(getClass());

	public void destroy() {
	}

	public void init() {
	}

	public String intercept(ActionInvocation invocation) throws Exception {
		try {
			return invocation.invoke();
		} catch (NullPointerException ne) {
			// 处理由上传文件过大引发的空指针异常
			//TODO:处理得不是很完善，需要修正
			ActionContext ac = invocation.getInvocationContext();
			HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);
			if (request instanceof MultiPartRequestWrapper) {
				MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;
				if (multiWrapper.hasErrors()) {
					String maxSize = Configuration.getString("webwork.multipart.maxSize");
					StringWriter sw = new StringWriter();
					ne.printStackTrace(new PrintWriter(sw));
					invocation.getInvocationContext().put(Constants.CONTEXT_EXCEPTION, "上传文件大小不能超过" + maxSize + "字节！");
					invocation.getInvocationContext().put(Constants.CONTEXT_EXCEPTION_INFO, sw.toString());
					return Constants.EXCEPTION;
				} else {
					handleException(invocation, ne);
				}
			} else {
				handleException(invocation, ne);
			}
			return Constants.EXCEPTION;
		} catch (Exception e) {
			handleException(invocation, e);
			return Constants.EXCEPTION;
		}

	}

	private void handleException(ActionInvocation invocation, Exception e) {
		String message = "Caught exception while invoking action: " + invocation.getAction();
		log.error(message, e);

		StringWriter sw = new StringWriter();
		e.printStackTrace(new PrintWriter(sw));
		invocation.getInvocationContext().put(Constants.CONTEXT_EXCEPTION, e.toString());
		invocation.getInvocationContext().put(Constants.CONTEXT_EXCEPTION_INFO, sw.toString());
	}
}
